package joalgo

import (
	"gitee.com/jolib/jokode"
	"github.com/bwmarrin/snowflake"
	"github.com/google/uuid"
	"time"
)

const uuidLen = 16

var idGeneratorInstance idGenerator

type UUID = uuid.UUID

type SnowID = snowflake.ID

type idGenerator interface {
	Generate() SnowID
}

type idGeneratorInternal struct {
}

func (g *idGeneratorInternal) Generate() snowflake.ID {
	return snowflake.ID(time.Now().UnixMilli())
}

func ResetSnowNode(node int64) {
	if sn, err := snowflake.NewNode(node); err != nil || sn == nil {
		jokode.Error("try generate new snow flake node fail, error info", err)
		idGeneratorInstance = new(idGeneratorInternal)
	} else {
		idGeneratorInstance = sn
	}
}

func init() {
	ResetSnowNode(time.Now().UnixMilli() % 1024)
}

func NewSnowId() SnowID {
	return idGeneratorInstance.Generate()
}

func NewUUID() UUID {
	return uuid.New()
}

func NewUUIDString() string {
	return uuid.NewString()
}

func GetUUIDFromString(id string) (UUID, error) {
	return uuid.Parse(id)
}

func GetUUIDFromStringMust(id string) UUID {
	x, err := GetUUIDFromString(id)
	if err != nil {
		panic(err)
	}
	return x
}

func GetUUIDString(id UUID) string {
	return id.String()
}

func UUIDEquals(u1, u2 UUID) bool {
	for i := 0; i < uuidLen; i++ {
		if u1[i] != u2[i] {
			return false
		}
	}

	return true
}
